#include <48func.h>
int setnonblock(int fd){
    int flag = fcntl(fd,F_GETFL);//获取已经打开的文件的状态
    flag = flag|O_NONBLOCK;//增加一个非阻塞的属性
    int ret = fcntl(fd,F_SETFL,flag);//设置文件的状态
    ERROR_CHECK(ret,-1,"fcntl");
    return 0;
}
int main(int argc, char *argv[])
{
    // ./1_server 192.168.118.128 1234
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_STREAM,0);//ipv4 tcp
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(atoi(argv[2]));
    // "1234" --> 小端的1234 --> 大端的1234
    serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
    // "192.168.118.128" 字符串 --> 大端的32bit的ip地址
    int ret = bind(sockfd,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
    // sockaddr_in 赋值 --> 取地址 --> 强转 sockaddr* 
    ERROR_CHECK(ret,-1,"bind");
    ret = listen(sockfd,10);
    ERROR_CHECK(ret,-1,"listen");
    // accept 从全连接队列中取出连接
    struct sockaddr_in clientAddr;
    socklen_t socklen = sizeof(clientAddr);//socklen必须初始化
    int netfd = accept(sockfd,(struct sockaddr *)&clientAddr,&socklen);
    ERROR_CHECK(netfd,-1,"accept");
    printf("client ip = %s, port = %d\n",
            inet_ntoa(clientAddr.sin_addr),
            ntohs(clientAddr.sin_port));
    //setnonblock(netfd);
    char buf[4096] = {0};
    while(1){
        ssize_t sret = recv(netfd,buf,sizeof(buf),MSG_DONTWAIT);
        if(sret == -1){
            printf("no data!\n");
            sleep(1);
        }
        else{
            printf("buf = %s\n", buf);
            break;
        }
    }
    return 0;
}






